import Axios from 'axios'

import Config from '../../config'

const state = {
  token: null
}

const getters = {
  getToken: state => state.token
}

const actions = {
  async login({ commit }, user) {
    const response = await Axios.post(`${Config.url}/login`, { ...user })
    if (response.data.message) {
      commit('tokenMutation', response.data)
    } else {
      console.log('login failed')
    }
  }
}

const mutations = {
  tokenMutation: (state, data) => {
    if (!localStorage.getItem('token')) {
      localStorage.setItem('token', data.token)
    }
    return (state.token = data.token)
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
